package com.dhruvtaara.beta.action;

import com.dhruvtaara.beta.model.entities.User;
import com.dhruvtaara.beta.model.persistance.Datastore;
import com.dhruvtaara.beta.model.viewmodel.UserRegister;
import com.dhruvtaara.beta.toolset.DefaultEncryption;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class RegisterAction {

	/**
	 * 
	 * @param userRegister
	 * @return
	 */
	public Key save(UserRegister userRegister) {
		DatastoreService datastore = Datastore.get();
		String password = DefaultEncryption.encrypt(userRegister.getPassword());
		Entity user = new Entity("User");
		user.setProperty("firstName", userRegister.getFirstName());
		user.setProperty("lastName", userRegister.getLastName());
		user.setProperty("emailAddress", userRegister.getEmailAddress());
		user.setProperty("primaryPhoneNumber", userRegister.getPhoneNumber());
		user.setProperty("password", password);
		datastore.put(user);

		Key userKey = user.getKey();

		Entity address = new Entity("Address", userKey);
		address.setProperty("line1", userRegister.getLine1());
		address.setProperty("city", userRegister.getCity());
		datastore.put(address);

		return userKey;
	}

	/**
	 * 
	 * @param emailId
	 * @return
	 */
	public boolean isAlreadyRegistered(String emailId) {
		DatastoreService datastore = Datastore.get();

		boolean exists = true;

		Query userQuery = new Query("User");
		userQuery
				.addFilter("emailAddress", Query.FilterOperator.EQUAL, emailId);

		PreparedQuery query = datastore.prepare(userQuery);

		Entity user = query.asSingleEntity();

		if (user == null) {
			exists = false;
		}
		return exists;
	}

	/**
	 * 
	 * @param userKey
	 * @return
	 */
	public User getUser(Key userKey) {
		DatastoreService datastore = Datastore.get();
		Entity userEntity;
		User user = new User();
		try {
			userEntity = datastore.get(userKey);
			user.setFirstName((String) userEntity.getProperty("firstName"));
			user.setLastName((String) userEntity.getProperty("lastName"));
		} catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return user;
	}
}
